package leetcode.median;

public class $8_MyAtoi {
    public int myAtoi(String s) {
        long res = 0l;
        int sign = 1;
        int i  = 0;
        while (i < s.length() && s.charAt(i) == ' ') i++;
        if (i == s.length()) return 0;

        if (s.charAt(i) == '-') {
            sign = -1;
            i++;
        } else if (s.charAt(i) == '+') {
            i++;
        }
        while (i < s.length() && Character.isDigit(s.charAt(i))) {
            res = res * 10 + (s.charAt(i) - '0') * sign;
            i++;
            if (res >= Integer.MAX_VALUE) {
                res = Integer.MAX_VALUE;
            } else if (res <= Integer.MIN_VALUE) {
                res = Integer.MIN_VALUE;
            }
        }
        return (int)res;
    }
}
